package com.sunshine.lnuplus.view.Login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.google.android.material.snackbar.Snackbar;
import com.sunshine.lnuplus.R;
import com.sunshine.lnuplus.databinding.ActivityLoginBinding;
import com.sunshine.lnuplus.utils.DatabaseHelper;
import com.sunshine.lnuplus.utils.DialogFragmentHelper;
import com.sunshine.lnuplus.utils.StatusBarUtils;
import com.sunshine.lnuplus.utils.TagHelper;
import com.sunshine.lnuplus.view.BaseActivity;
import com.sunshine.lnuplus.view.Main.MainActivity;

public class LoginActivity extends BaseActivity {

    private ActivityLoginBinding binding;
    private SharedPreferences rememberPassword;
    private SharedPreferences.Editor editor;
    private DialogFragmentHelper dialogFragmentHelper;
    private LoginViewModel viewModel;
    private boolean firstStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_login);
        viewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        StatusBarUtils.with(this).setColor(-2).init();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        firstStart = getIntent().getBooleanExtra("first_start",false); //接收是否第一次启动
        binding.loginLayout.setBackgroundColor(StatusBarUtils.getColorPrimary(this));
        rememberPassword = getSharedPreferences("remember_password",MODE_PRIVATE);
        editor = rememberPassword.edit();

        initLogin();
        binding.toLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logining();
                viewModel.toLogin(getApplicationContext(),binding.editTextUser.getText().toString(),binding.editTextPassword.getText().toString());
            }
        });
        viewModel.getResultData().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if(integer!=1&&integer!=0) loginFail(integer);
                if(integer==1) loginSuccess();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if(firstStart) startActivity(new Intent(this,MainActivity.class));
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if(firstStart) startActivity(new Intent(this,MainActivity.class));
            finish();
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }

    //如果记住密码则填写，否则就填写账号
    private void initLogin() {

        SQLiteDatabase database;
        database = DatabaseHelper.getDatabase(getApplicationContext(),"timetable.db");
        Cursor cursor = database.query("user",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            binding.editTextUser.setText(cursor.getString(cursor.getColumnIndex("uno")));
        }
        if(rememberPassword.getBoolean("remember",false)){
            binding.editTextPassword.setText(cursor.getString(cursor.getColumnIndex("upassword")));
            binding.rememberPassword.setChecked(true);
        }
        cursor.close();
    }

    //无论成功失败不保存密码都生效
    private void logining() {
        if(!binding.rememberPassword.isChecked()){
            editor.putBoolean("remember",false);
            editor.apply();
        }
        StatusBarUtils.hideSoftInput(getApplicationContext(),new EditText[]{binding.editTextUser,binding.editTextPassword});
        initDialog();
        DatabaseHelper.passwordToDB(getApplicationContext(),binding.editTextUser.getText().toString(),"");//记住用户名
    }

    //登录成功操作：如果记住密码则储存到数据库，改变记住密码sp
    public void loginSuccess() {
        dialogFragmentHelper.dismiss();
        if(binding.rememberPassword.isChecked()){
            DatabaseHelper.passwordToDB(this,binding.editTextUser.getText().toString(),binding.editTextPassword.getText().toString());
            editor.putBoolean("remember",true);
            editor.apply();
        }
        if(firstStart){
            startActivity(new Intent(this,MainActivity.class).putExtra("first_start_success",true));
            finish();
        }else {
            setResult(TagHelper.LOGIN);
            finish();
        }
    }

    public void loginFail(int state) {
        dialogFragmentHelper.dismiss();
        String toast = null;
        switch (state){
            case -2:
                toast = getResources().getString(R.string.login_fail1);
                break;
            case -1:
                toast = getResources().getString(R.string.login_fail2);
                break;
            case -3:
                toast = getResources().getString(R.string.login_fail3);
        }
        Snackbar.make(binding.loginLayout,toast,Snackbar.LENGTH_SHORT).show();
    }

    private void initDialog(){
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_progress,null);
        TextView textView = view.findViewById(R.id.progress_text);
        textView.setText(getString(R.string.logining_message));
        dialogFragmentHelper = DialogFragmentHelper.newInstance(getString(R.string.logining_title),null,null,view,false,null,null);
        dialogFragmentHelper.show(getSupportFragmentManager(),"");
    }
}
